package com.lingchou.cloud.process.client.service.impl;

import cn.hutool.core.util.StrUtil;
import com.lingchou.cloud.process.client.service.ProcessCheckService;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.springframework.stereotype.Service;

@Service
public class ProcessCheckServiceImpl implements ProcessCheckService {
    private final RepositoryService repositoryService;
    private final RuntimeService runtimeService;
    private final HistoryService historyService;
    private final TaskService taskService;

    public ProcessCheckServiceImpl(RepositoryService repositoryService, RuntimeService runtimeService, HistoryService historyService, TaskService taskService) {
        this.repositoryService = repositoryService;
        this.runtimeService = runtimeService;
        this.historyService = historyService;
        this.taskService = taskService;
    }

    @Override
    public boolean checkDefinitionInvalid(String definitionId) {
        return StrUtil.isNotEmpty(definitionId) &&
                repositoryService.createProcessDefinitionQuery().processDefinitionId(definitionId).singleResult() == null;
    }

    @Override
    public boolean checkProcessInstanceInvalid(String processInstanceId, boolean running) {
        return StrUtil.isNotEmpty(processInstanceId) &&
                (running ?
                        runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null :
                        historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null);
    }

    @Override
    public boolean checkTaskInvalid(String taskId) {
        return StrUtil.isNotEmpty(taskId) &&
                taskService.createTaskQuery().taskId(taskId).singleResult() == null;
    }
}
